<?php

namespace App\Install\Controller;

use App\Common\Model\Model;
use App\Common\Util\Response;
use App\Common\Util\TP;
use App\Install\Service\InitService;
use think\facade\Log;
use think\response\Redirect;

/**
 * 系统初始化
 *
 * Class InitController
 */
class IndexController
{
    /**
     * 初始化页面
     *
     * @return string|\think\Response|Redirect
     * @throws \Exception
     */
    public function index(): string|\think\Response|Redirect
    {
        if (InitService::isInitComplete()){
            return TP::request()->isPost()
                ? Response::json()->fail("已经初始化完成，无需重复操作")
                : Response::redirect('/');
        }

        if (TP::request()->isPost()) {
            return $this->initialize();
        }

        return Response::render('Init/index');
    }

    /**
     * 执行初始化
     *
     * @return \think\Response
     * @throws \Exception
     */
    public function initialize(): \think\Response
    {
        $errorMsg = InitService::aop()->init();

        $prefixTip = '';
        if (!Model::getPrefix()) {
            $prefixTip = "<span style='color: red;'>请修改数据库配置前缀为: <b>sc_</b></span>\n";
        }

        return Response::json()->success(message: "<b>初始化完成</b>\n如失败信息不为空，请解决后重新初始化\n{$prefixTip}失败信息:\n" . implode("\n", $errorMsg));
    }
}